<?php

namespace App\Http\Controllers\Admin\Dispatch;

use App\Http\Controllers\Controller;
use App\Models\OrderModel;
use App\Models\ReturnItemModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

//退货
class ReturnItem extends Controller
{

    public function list(Request $request) {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);
        $order_sn = $request->input('order_sn', '');
        $status = $request->input('status', '');
        $create_start = $request->input('create_start', '');
        $create_end = $request->input('create_end', '');

        $query = ReturnItemModel::query()->with(['create_admin'])->whereHas('order', function($query) use ($order_sn) {
            $query->where('sn', 'like', '%'.$order_sn.'%');
        });

        if($status) {
            $query->where('status', $status);
        }

        if($create_start && $create_end){
            $query = $query->whereBetween('created_at', [$create_start, $create_end]);
        }

        $total = $query->count('id');
        $items = $query
            ->offset(($page-1) * $limit)
            ->limit($limit)
            ->orderBy('id', 'desc')
            ->get();

        $list = $items->map(function($item) {
            $log = [];
            $log[] = [
                'time' => $item->created_at->toDateTimeString(),
                'event' => '登记退货',
                'operator' => $item->create_admin->staff->name ?? '',
            ];

            if($item->storage_time) {
                $log[] = [
                    'time' => $item->storage_time,
                    'event' => '退货入库',
                    'operator' => $item->storage_admin->name ?? '',
                ];
            }

            if($item->out_stock_time) {
                $log[] = [
                    'time' => $item->out_stock_time,
                    'event' => '退货出库',
                    'operator' => $item->out_stock_admin->name ?? '',
                ];
            }
            
            return [
                'id' => $item->id,
                'customer_name' => $item->order->customer->name ?? '',
                'customer_sn' => $item->order->customer->sn ?? '',
                'take_order_sn' => $item->order->take_order->sn ?? '',
                'sn' => $item->order->sn ?? '',
                'big_pkg_no' => $item->big_pkg_no,
                'small_pkg_no' => $item->small_pkg_no,
                'created_at' => $item->created_at->toDateTimeString(),
                'place' => $item->place->name ?? '',
                'status_name' => ReturnItemModel::STATUS_MAPS[$item->status] ?? '',
                'remark' => $item->remark,
                'source' => ReturnItemModel::SOURCE_MAPS[$item->source] ?? '',
                'log' => $log,
            ];
        });

        return $this->success(['list' => $list, 'total' => $total]);
    }

    public function add(Request $request){
        $params = $request->all();
        $validator = Validator::make($params, [
            'sn' => 'required',
            'status' => 'required|in:1,2,3',
        ], [
            'sn.required' => '请填写入仓号',
            'status.required' => '请选择退货状态',
            'status.in' => '退货状态错误',
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }

        $order = OrderModel::where('sn', $params['sn'])->first();
        if(!$order){
            return $this->error('入仓单不存在');
        }

        // $place = PlaceModel::find($params['dispatch_place_id']);
        // if(!$place){
        //     return $this->error('库位不存在');
        // }

        if($order->status == OrderModel::STATUS_RETURN){
            return $this->error('运单已退件,不能重复退件');
        }

        $auth = $request->get('auth');
        try{
            DB::transaction(function () use ($params, $order, $auth) {
                $model = new ReturnItemModel();
                $model->order_id = $order->id;
                $model->dispatch_place_id = $params['dispatch_place_id'] ?? 0;
                $model->status = $params['status'];
                $model->big_pkg_no = $params['big_pkg_no'] ?? '';
                $model->small_pkg_no = $params['small_pkg_no'] ?? '';
                $model->remark = $params['remark'] ?? '';
                $model->created_admin_id = $auth->id;
                $model->save();

                $order->status = OrderModel::STATUS_RETURN;
                $order->save();
            });
        } catch(\Exception $e) {
            return $this->error($e->getMessage());
        }

        return $this->success();
    }

    //入库
    public function storage(Request $request) {
        $ids = $request->input('ids');
        $place_id = $request->input('place_id', '');
        if(!is_array($ids)) {
            return $this->success();
        }

        if(!$place_id){
            return $this->error('请选择库位');
        }

        $auth = $request->get('auth');

        $res = ReturnItemModel::whereIn('id', $ids)
            ->where('status', ReturnItemModel::STATUS_WAIT_STORAGE)
            ->update([
                'status' => ReturnItemModel::STATUS_STORAGE,
                'dispatch_place_id' => $place_id,
                'storage_time' => date('Y-m-d H:i:s'),
                'storage_admin_id' => $auth->id
            ]);

        return $this->success();
    }

    //出库
    public function out(Request $request) {
        $ids = $request->input('ids');
        if(!is_array($ids)) {
            return $this->success();
        }

        $auth = $request->get('auth');
        ReturnItemModel::whereIn('id', $ids)
            ->where('status', ReturnItemModel::STATUS_STORAGE)
            ->update([
                'status' => ReturnItemModel::STATUS_OUT_STOCK,
                'out_stock_time' => date('Y-m-d H:i:s'),
                'out_stock_admin_id' => $auth->id
            ]);
        return $this->success();
    }

}
